<?php
/**
 * Created by PhpStorm.
 * User: 跳梁
 * Date: 2016/4/18
 * Time: 10:25
 */
class SecurityAction extends Action{
    public function securityList($name='',$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $securityModel = M("module_security");
        Session::switchCustomer($cid);
        $where['a.customerId'] = array('eq',$cid);
        $where['a.name'] = array('like',"%$name%");
        $where['a.deleted']= array('eq',0);
        $result = $securityModel->alias('a')
            ->join("left join wx_module_security_code b on a.id=b.securityId and b.type = 1")
            ->where($where)
            ->field('a.name,a.name,a.batch,a.amount,a.id,count(b.id) as securitySum')
            ->order('a.updateTime')
            ->group("a.id")
            ->limit($start,$limit)
            ->select();
        if($result){
            $count = $securityModel->alias('a')
                ->join("inner join wx_module_security_code b on a.id=b.securityId")
                ->where($where)
                ->field('a.name,a.name,a.batch,a.amount,a.id,sum(b.id) as securitySum')
                ->group("a.id")
                ->count();
            Output::instance()->objArray($result,$count);
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    //详情
    public function getSecurityById($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $securityModel = M("module_security");
        Session::switchCustomer($cid);
        $where['a.id']=array('eq',$id);
        $result = $securityModel->alias("a")
            ->join("wx_pb_template b on a.templateId=b.id")
            ->field("a.*,b.id as templateId,b.tplname as templateName")
            ->where($where)->find();
        if($result["proImgs"]){
            $result["proImgs"]=json_decode($result["proImgs"],true);
        }
        if($result["json"]){
            $result["json"]=json_decode($result['json'],true);
        }
        Output::instance()->object($result);
    }
    //保存
    public function saveSecurity($name,$batch,$amount,$templateId,$shareTitle,$shareImg,$shareDescrip,$proLogo,
                                 $proTitle,$proImgs,$securityInfo,$proContent,$followUrl,$json,$id=null){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $securityModel = M("module_security");
        $securityCode = M("module_security_code");
        Session::switchCustomer($cid);
        $data["name"]=$name;
        $data["batch"]=$batch;
        $data["amount"]=$amount;
        $data["templateId"]=$templateId;
        $data["shareTitle"]=$shareTitle;
        $data["shareImg"]=$shareImg;
        $data["shareDescrip"]=$shareDescrip;
        $data["proLogo"]=$proLogo;
        $data["proTitle"]=$proTitle;
        $data["proImgs"]=$proImgs;
        $data["securityInfo"]=$securityInfo;
        $data["proContent"]=$proContent;
        $data["followUrl"]=$followUrl;
        $data["deleted"]=0;
        $data["cutomerId"]=$cid;
        $data["createTime"]=date("Y-m-d H:i:s");
        $data["json"]=$json;
        $data["customerId"]=$cid;
        $securityModel->startTrans();
        if($id){
            $result = $securityModel->where("id=$id")->save($data);
        }else{
            $data["createTime"]=date("Y-m-d H:i:s");
            $result = $securityModel->add($data);
            //      生成防伪码  $amount
            $codeData = array();
            for($i=0;$i<$amount;$i++){
                $temp['securityId']=$result;
                do{
                    $verificationCode = self::createSecurityCode();
                    $codeResult = false;
                    foreach($codeData as $value){
                        if($value['verificationCode']==$verificationCode){
                            $codeResult=true;
                        }
                    }
                }while($codeResult);
                $temp['verificationCode'] =$verificationCode;
                array_push($codeData,$temp);
            }
            $codeReuslt = $securityCode->addAll($codeData);
            if(!$codeReuslt){
                $securityModel->rollBack();
                Output::instance()->resultCode(code_sql_error);
                return;
            }
        }
        if($result){
            $securityModel->commit();
            Output::instance()->resultCode();
        }else{
            $securityModel->rollBack();
            Output::instance()->resultCode(code_sql_error);
        }

    }

    public function securityDetailList($id,$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $securityCode = M("module_security_code");
        Session::switchCustomer($cid);
        $result = $securityCode->alias("a")
            ->join("wx_".$cid."_user_weixin_info b on a.userName=b.openid")
            ->where("a.securityId = $id")
            ->field("a.*,b.headimgurl,b.nickname")
            ->limit($start,$limit)
            ->order('a.type desc')
            ->select();
        if($result){
            $count = $securityCode->alias("a")
                ->join("wx_".$cid."_user_weixin_info b on a.userName=b.openid")
                ->where("a.securityId = $id")
                ->field("a.*,b.headimgurl,b.nickname")
                ->order('a.type desc')
                ->count();
            Output::instance()->objArray($result,$count);
        }else{
            Output::instance()->resultCode(code_sql_error);
        }

    }
    //删除
    public function delete($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $securityModel = M("module_security");
        $securityCode = M("module_security_code");
        Session::switchCustomer($cid);
        $securityModel->startTrans();
        $data["deleted"]=1;
        $data["updateTime"]=date("Y-m-d H:i:s");
        $result = $securityModel->where("id=$id")->save($data);
        $codeDeta["type"]=2;
        $codeResult = $securityCode->where("securityId=$id")->save($codeDeta);
        if($result!==false&&$codeResult!==false){
            $securityModel->commit();
            Output::instance()->resultCode();
        }else{
            $securityModel->rollBack();
            Output::instance()->resultCode(code_sql_error);
        }

    }
    //下载
    public function downloadCode($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $securityCode = M("module_security_code");
        Session::switchCustomer($cid);
        $result = $securityCode->where("securityId=$id")->field('verificationCode,type,validateTime')->order("type desc")->select();
        $data[0] = array(
            'verificationCode'=>'验证码',
            'type'=>'验证状态'
        );
        foreach ($result as $k1 => $v1) {
            if($v1['type']==1){
                $v1['type']='已验证';
            }elseif($v1['type']==2){
                $v1['type']='已删除';
            }else{
                $v1['type']='未验证';
            }
            $data[] = $v1;
        }
        Output::instance()->objArrayCsv($data,null,'防伪验证码'.date("Y-m-d H:i:s").'.csv');
    }
    //获得链接和二维码
    public function getSecurityInfo($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $securityModel = M("module_security");
        Session::switchCustomer($cid);
        $securityInfo = $securityModel->where("id=$id")->field("shortUrl,qrcode")->find();
        if(!$securityInfo['shortUrl']){
            $p=new stdClass();
            $p->id=$id;
            $p=json_encode($p);
            $url = C('SERVER_HOST') . "call.html?customerId={$cid}&module=security&method=index&params=$p";
            $url = WeixinApi::long2short($url);
            $url = json_decode($url);
            if(!$url->errcode){
                $url = $url->short_url;
            }else{
                Output::instance()->resultCode(1,"链接转换失败");
                return;
            }
            $data['shortUrl']=$url;
        }else{
            $url = $securityInfo['shortUrl'];
        }
        $arr['shortUrl']=$url;
        if(!$securityInfo['shortUrl']||!$securityInfo["qrcode"]){
            $fname="securityCode".time().".png";
            $fileName=LOCAL_PIC_PATH . "$fname";
            PhpQRcode::png($url, $fileName, 'L', 9,4);
            if(file_exists($fileName)){
                $out=R("Upload/uploadLocalFileToOss",array($fname,$fileName));
                if(!$out->code){
                    $qrImg = $out->path;
                    $data['qrcode']=$qrImg;
                }
            }
        }else{
            $qrImg = $securityInfo["qrcode"];
        }
        $arr['qrcode']=$qrImg;
        if(isset($data)&&$data){
            $result = $securityModel->where("id=$id")->save($data);
        }
        Output::instance()->object($arr);
    }

    //模板
    public function getTemplate(){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $templateModel = M("pb_template");
        Session::switchCustomer($cid);
        $where['module']=array('eq',"security");
        $result['list'] = $templateModel->where($where)->select();
        if($result){
            Output::instance()->object($result);
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    protected function createSecurityCode( $length = 10 ) {
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }

}